<?php

namespace app\admin\controller\distribution;
use app\common\model as M;
use app\admin\controller\AuthController;
use app\admin\model\system\SystemConfig as ConfigModel;
use app\common\model\DistributionCommission;
use app\common\model\DistributionConfig;
use app\common\model\DistributionOrder;
use app\common\model\DistributionUser;
use app\common\model\Organ;
use app\common\model\User as UserModel;
use service\FormBuilder as Form;
use service\JsonService;
use service\UploadService;
use think\Db;
use think\Log;
use think\Url;

/**
 *  分销用户
 * Class SystemConfig
 * @package app\admin\controller\system
 */
class User extends AuthController
{
    /**
     * 基础配置
     * */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 机构用户列表
     */
    public function get_list()
    {
        $user = $this->adminInfo;
        if($user['level']==0){
            $wheres = [ "eb_distribution_user.is_del" => 0];
        }else{
            $wheres = ["eb_distribution_user.org_id" => $user['org_id'], "eb_distribution_user.is_del" => 0];
        }
        $userHasWheres = [];
        if(input('org_id')){
            $wheres['org_id'] = input('org_id');
        }
        if (input('role_id')) {
            $wheres['role_id'] = input('role_id');
        }
        if (input('status')) {
            $wheres['eb_distribution_user.status'] = input('status');
        }
        if (input('last_time')) {
            $userHasWheres['last_time'] = ['between', [strtotime(input('last_time') . " 00:00:00"), strtotime(input('last_time') . " 23:59:59")]];
        }
        if (input('nickname')) {
            $userHasWheres['nickname'] = ['like', input('nickname') . '%'];
        }
        if (input('mobile')) {
            $wheres['mobile'] = input('mobile');
        }
        if (input('pid')) {
            $wheres['pid'] = input('pid');
        }
        $count = DistributionUser::where($wheres)->count();
        $result = DistributionUser::hasWhere('user', $userHasWheres)->with('user', 'puser','organ')->where($wheres)->order('id','desc')->paginate(10);

        foreach ($result as $k => $v) {
            $data = [
                'id' => $v['id'],
                'nickname' => $v['user']['nickname'],
                'avatar' => $v['user']['avatar'],
                //'role' => $v['role_id'] == 1 ? '家长' : '学生',
                'mobile' => $v['mobile'],
                'add_time' => date('Y-m-d H:i:s', $v['user']['add_time']),
                'last_time' => date('Y-m-d H:i:s', $v['user']['last_time']),
                'pnickname' => $v['puser']['nickname'],
                'balance' => $v['balance'],
                'withdrawed_amount' => $v['withdrawed_amount'],
                'status' => $v['status'],
                'organ_name'=>$v['organ']['organ_name']
            ];
            $result[$k] = $data;
        }
        return JsonService::successlayui(['count' => $count, 'data' => $result]);
    }

    /**
     * 获取分销用户列表（选择上级用户）
     */
    public function getUserList()
    {
        $user = $this->adminInfo;
        $result = Db::query("select concat(eb_user.nickname,'   ',eb_user.mobile) as nickname,eb_user.uid as id from eb_distribution_user left join eb_user on eb_user.uid = eb_distribution_user.user_id where eb_distribution_user.status =1 and eb_distribution_user.is_del=0 and eb_distribution_user.org_id = " . $user['org_id']);
        return JsonService::successful("success", $result);
    }

    /**
     * 更新分销用户状态（启用或停用用户）
     */
    public function updateUserStatus($id)
    {
        $user = DistributionUser::get($id);
        $user->status = input('status');
        $user->save();
        return JsonService::successful("更新成功");
    }

    /**
     * 删除分销用户
     */
    public function delete($id)
    {
        $user = DistributionUser::get($id);
        $user->is_del = 1;
        $user->save();
        return JsonService::successful("删除成功");
    }

    /**
     * 分销用户详情页
     */
    public function edit($id)
    {
        $this->assign('id', $id);
        return $this->fetch('distribution/user/edit');
    }

    /**
     * 获取分销用户详情
     */
    public function getUserDetail($id)
    {
        $distrubutionUser = DistributionUser::get($id);
        $result = ['distribution_user' => $distrubutionUser];
        $user = UserModel::get($distrubutionUser->user_id);
        $result['user'] = $user;
        return JsonService::successful("成功", $result);
    }

    /**
     * 更新分销用户信息
     */
    public function updateUserInfo($id)
    {
        $distrubutionUser = DistributionUser::get($id);
        if (request()->has('level')) {
            $distrubutionUser->level = input('level');
        }
        if (request()->has('role_id')) {
            $distrubutionUser->role_id = input('role_id');
        }
        if (request()->has('pid')) {
            $distrubutionUser->pid = input('pid');
        }
        if (request()->has('mobile')) {
            $distrubutionUser->mobile = input('mobile');
        }
        $distrubutionUser->save();
        $result = ['distribution_user' => $distrubutionUser];
        $user = UserModel::get($distrubutionUser->user_id);
        $result['user'] = $user;
        return JsonService::successful("成功", $result);
    }

    /**
     * 获取用户佣金记录
     */
    public function getCommissionRecord($id)
    {
        $user=DistributionUser::get($id);
        $start = input('start');
        $end = input('end');
        $wheres = [];
        if ($start && $end) {
            $wheres['create_time'] = ['between', [$start, $end]];
        }
        $result = DistributionCommission::where('user_id',$user->user_id)->where($wheres)->order('id','desc')->paginate(10);
        foreach ($result as $k => $v) {
            switch ($v['order_type']) {
                case 1:
                    $v['order_type'] = '直推订单';
                    break;
                case 2:
                    $v['order_type'] = '裂变订单';
                    break;
                default:
                    $v['order_type'] = '-';
            }
            $v['type'] = $v['type'] == 1 ? '入账' : '提现';
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $result[$k] = $v;
        }
        return JsonService::successful($result);
    }

    /**
     * 获取下级用户列表
     */
    public function getDownUserList($id)
    {
        $duser = DistributionUser::get($id);
        $wheres = ['pid' => $duser->user_id, 'is_del' => 0];
        $result = DistributionUser::with('user')->where($wheres)->order('id','desc')->paginate(10);
        foreach ($result as $k => $v) {
            $result[$k] = [
                'id' => $v['id'],
                'nickname' => $v['user']['nickname'],
                'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                'mobile' => $v['mobile'],
                'total_order_amount' => $v['total_order_amount'],
                'total_com' => $v['total_com']
            ];
        }
        return JsonService::successful($result);
    }

    /**
     * 直销订单列表
     */
    public function getDirectOrderData($id)
    {
        $start = input('start');
        $end = input('end');
        $duser = DistributionUser::get($id);
        $wheres = ["do.user_id" => $duser->user_id,'do.org_id'=>$duser->org_id];
        if ($start && $end) {
            $wheres['do.create_time'] = ['between', [$start, $end]];
        }
        //$result = DistributionOrder::with(['enroll.course'])->where($wheres)->order('id','desc')->paginate(10);
        $result = DistributionOrder::alias('do')->field('do.*,o.order_no')->join('__ORDER__ o' , 'do.relation_id = o.id' , 'left')->where($wheres)->order('do.id','desc')->paginate(10);
        foreach ($result as $k => $v) {
            $result[$k] = [
                'id' => $v['id'],
                'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                'order_no' => $v['order_no'],
                'goods_name' => $v['relation_name'],
                'order_amount' => $v['order_amount'],
                'commission' => $v['commission'],
            ];
        }
        return JsonService::successful($result);
    }

    /**
     * 分销订单列表
     */
    public function getFissionOrderData($id)
    {
        $start = input('start');
        $end = input('end');
        $duser = DistributionUser::get($id);
        $wheres = ["do.p_user_id" => $duser->user_id,'do.org_id'=>$duser->org_id];
        if ($start && $end) {
            $wheres['do.create_time'] = ['between', [$start, $end]];
        }
        //$result = DistributionOrder::with(['duser', 'enroll.course'])->where($wheres)->order('id','desc')->paginate(10);
        $result = DistributionOrder::alias('do')->with(['duser'])->field('do.*,o.order_no')->join('__ORDER__ o' , 'do.relation_id = o.id' , 'left')->where($wheres)->order('do.id','desc')->paginate(10);
        foreach ($result as $k => $v) {
            $result[$k] = [
                'id' => $v['id'],
                'user_name' => $v['duser']['nickname'],
                'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                'order_no' => $v['order_no'],
                'goods_name' => $v['relation_name'],
                'order_amount' => $v['order_amount'],
                'commission' => $v['p_commission'],
            ];
        }
        return JsonService::successful($result);
    }

    public function getOrganList()
    {
        $user = $this->adminInfo;
        $isAdmin=$user['level']==0?1:0;
        $result=[
            'isAdmin'=>$isAdmin,
            'organs'=>Organ::where('is_del',0)->field("organ_name,id")->select()
        ];
        return JsonService::successful($result);
    }
}
